package com.ruoyi.sale.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.MonthlyCardMsg;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.mapper.MonthlyCardMsgMapper;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.product.domain.Product;
import com.ruoyi.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.sale.auditStatusMachine.ServiceFactory;
import com.ruoyi.sale.auditStatusMachine.StatusService;
import com.ruoyi.sale.domain.*;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.domain.WarehousingRecords;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import com.ruoyi.warehousing.mapper.WarehousingRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WangChangShuo
 * @date 2022年05月09日 17:42
 */
@Service
public class SaleGoodsServiceImpl implements ISaleGoodsService {

    @Autowired
    SaleGoodsMapper saleGoodsMapper;

    @Autowired
    AuditMapper auditMapper;

    @Autowired
    WarehousingMapper warehousingMapper;

    @Autowired
    WarehousingRecordsMapper warehousingRecordsMapper;

    @Autowired
    SaleorderMapper saleorderMapper;

    @Autowired
    PurchaseOrderMapper purchaseOrderMapper;


    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    private MonthlyCardMsgMapper monthlyCardMsgMapper;

    /**
     * 查新销货单数据集合
     *
     * @param saleGoodsOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsList(SaleGoodsOrder saleGoodsOrder) {
        return saleGoodsMapper.selectSaleGoodsList(saleGoodsOrder);
    }

    /**
     * 用与查询销货单子表状态未完成的
     *
     * @param saleGoodsOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsListInvoice(SaleGoodsOrder saleGoodsOrder) {
        return saleGoodsMapper.selectSaleGoodsListInvoice(saleGoodsOrder);
    }

    /**
     * 查询销货单子表数据
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public SaleGoodsModel selectSaleGoodsModel(HashMap<Object, Object> hashMap) {
        return saleGoodsMapper.selectSaleGoodsModel(hashMap);
    }

    /**
     * 插入销货单集合数据
     *
     * @param saleGoodsOrder 插入数据
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSaleGoodsOrder(SaleGoodsOrder saleGoodsOrder) {
        saleGoodsOrder.setExpressStatus("0"); // 默认未下单
        return saleGoodsMapper.insertSaleGoodsOrder(saleGoodsOrder);
    }

    @Override
    public int addAfter(SaleGoodAfter saleGoodAfter) {
        return saleGoodsMapper.addAfter(saleGoodAfter );
    }

    /**
     * 插入销货单子表数据
     *
     * @param saleGoodsModel 插入子表数据
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSaleGoodsModels(SaleGoodsModel saleGoodsModel) {
        return saleGoodsMapper.insertSaleGoodsModels(saleGoodsModel);
    }

    /**
     * 查询销货单数据集合
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public SaleGoodsOrder selectSaleGoodsById(HashMap<String, Object> hashMap) {
        return saleGoodsMapper.selectSaleGoodsById(hashMap);
    }

    public Boolean countSalesOrderEdit(Long saleGoodsId, List<SaleNumRecord> saleNumRecords, List<SaleNumRecord> saleNumRecordLists) {
        List<SaleNumRecord> saleNumRecords1 = saleGoodsMapper.selectSaleNumRecordById(saleGoodsId);
        List<SaleorderModel> saleorderModelList = new ArrayList<>();

        for (SaleNumRecord saleNumRecord : saleNumRecords1) {
            for (int i = saleNumRecords.size() - 1; i >= 0; i--) {
                if (saleNumRecord.getSaleorderModelId().equals(saleNumRecords.get(i).getSaleorderModelId())) {
                    saleNumRecords.remove(i);
                }
            }
        }
        List<Long> longs = new ArrayList<>();
        for (SaleNumRecord saleNumRecord : saleNumRecords) {
            longs.add(saleNumRecord.getNumRecordId());
        }
        if (longs.size() > 0) {
            saleGoodsMapper.deleteSaleNumRecordList(longs);
        }

        for (SaleNumRecord saleNumRecord : saleNumRecords) {
            Long saleorderModelId = saleNumRecord.getSaleorderModelId();
            SaleorderModel saleorderModel1 = saleorderMapper.selectSaleModelByModelId(saleorderModelId);
            int executeNum = saleNumRecord.getExecuteNum();
            int remainingNum = saleNumRecord.getRemainingNum();
            saleorderModel1.setRemainingNum(remainingNum + executeNum);
            saleorderModel1.setExecuteNum(saleorderModel1.getExecuteNum() - executeNum);
            if (saleorderModel1.getExecuteNum() == 0) {
                saleorderModel1.setExecuteStatus("0");
            }
            saleorderModelList.add(saleorderModel1);
        }
        if (saleorderModelList.size() != 0) {
            saleorderMapper.updateSaleorderModelList(saleorderModelList);
        }
        return true;
    }

    /**
     * 审核销售订单修改
     *
     * @param saleGoodsId 销货单主键
     * @return 结果
     */
    @Override
    public Boolean auditSalesOrderEdit(Long saleGoodsId) {
        List<SaleorderModel> saleorderModels = saleGoodsMapper.selectAuditReject(saleGoodsId);
        for (SaleorderModel saleorderModel : saleorderModels) {
            saleorderMapper.updateSaleorderModela(saleorderModel);
        }
        return true;
    }

    /**
     * 修改保存销货单信息
     *
     * @param saleGoodsOrder 销货单数据
     * @param saleorderOrder 销售订单数据
     * @return 结果
     */
    @Transactional
    @Override
    public int editSave(SaleGoodsOrder saleGoodsOrder, SaleorderOrder saleorderOrder) {
        //修改审核表
        Audit audit = new Audit();
        //销货单为3
        audit.setOrderType("3");
        //业务员
        audit.setUserId(saleGoodsOrder.getUserId());
        //客户公司id
        audit.setSupplierId(saleGoodsOrder.getCustomerId());
        //含税金额
        audit.setTaxAmount(saleGoodsOrder.getSaleGoodsTaxamount());
        //订单id
        audit.setOrderId(saleGoodsOrder.getSaleGoodsId());
        //订单编号
        audit.setOrderNum(saleGoodsOrder.getSaleGoodsNum());
        auditMapper.updateAuditOther(audit);
        //更新主表 金额
        saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
        //判断子表 是否为空
        if (saleGoodsOrder.getSaleGoodsModels() != null) {
            //不为空 查询自己 用来做比较
            List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder.getSaleGoodsModels();
            //新建对比数组，用于判断执行什么操作
            ArrayList<Long> arrayList = new ArrayList();
            //根据销售订单id  查询 原来的自己的数据
            Long saleGoodsId = saleGoodsOrder.getSaleGoodsId();
            List<SaleGoodsModel> saleGoodsModels1 = saleGoodsMapper.selectSaleGoodsModelById(saleGoodsId);
            for (int i = 0; i < saleGoodsModels.size(); i++) {
                saleGoodsModels.get(i).setSaleGoodsModelId(null);
                saleGoodsModels.get(i).setSaleGoodsId(saleGoodsOrder.getSaleGoodsId());
            }
            for (SaleGoodsModel model : saleGoodsModels1) {
                arrayList.add(model.getSaleGoodsModelId());
            }
            ArrayList<Long> saleorderModelList = new ArrayList();
            for (SaleGoodsModel model : saleGoodsModels) {
                if (model.getSaleGoodsModelId() != null) {
                    saleGoodsMapper.updateSaleGoodsModel(model);
                    saleorderModelList.add(model.getSaleGoodsModelId());
                } else {
                    saleGoodsMapper.insertSaleGoodsModels(model);
                }
            }
            //数组中剩余的数就是需要删除的数据
            for (Long o1 : saleorderModelList) {
                Iterator<Long> iterator = arrayList.iterator();
                while (iterator.hasNext()) {
                    if (iterator.next().equals(o1)) {
                        iterator.remove();
                    }
                }
            }
            //要更新掉的saleordermodel集合
            List<SaleorderModel> models = null;
            for (int i = 0; i < arrayList.size(); i++) {
                SaleGoodsModel saleGoodsModel = saleGoodsMapper.selectSaleGoodsModelByModelId(arrayList.get(i));
                HashMap<String, Long> hashMap = new HashMap<>();
                hashMap.put("saleGoodsId", saleGoodsModel.getSaleGoodsId());
                models = saleorderMapper.selectBatchModelBySaleGoodsId(hashMap);
            }
            if (models != null) {
                for (int i = 0; i < models.size(); i++) {
                    saleorderMapper.updateSaleorderModela(models.get(i));
                }
            }
            if (arrayList.size() != 0) {
                saleGoodsMapper.deleteSaleGoodsModelById(arrayList);
            }
        }
        //修改销售订单 执行数量 和剩余数量
      /*  for (int j = 0; j < saleorderOrder.getSaleorderModels().size(); j++) {
            SaleorderModel saleorderModel = saleorderOrder.getSaleorderModels().get(j);
            if (saleorderModel.getRemainingNum() == 0) {
                //已执行
                saleorderModel.setExecuteStatus("1");
            } else if (saleorderModel.getExecuteNum() == 0) {
                //未执行
                saleorderModel.setExecuteStatus("0");
            } else {
                //部分执行
                saleorderModel.setExecuteStatus("2");
            }
            //   saleorderMapper.updateSaleorderModela(saleorderModel);
        }
*/
        //将之前的model 数据删掉
//        Long saleGoodsId = saleGoodsOrder.getSaleGoodsId();
//        saleGoodsMapper.deleteSaleGoodsModelBySaleGoodsId(saleGoodsId);
//        int num = 0;
//        for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size(); i++) {
//            SaleGoodsModel saleGoodsModel = saleGoodsOrder.getSaleGoodsModels().get(i);
//            saleGoodsModel.setSaleGoodsId(saleGoodsId);
//            num = saleGoodsMapper.insertSaleGoodsModels(saleGoodsModel);
//        }
        return 1;
    }

    /**
     * 查询销货单数据
     *
     * @param companyId 公司主键
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsCustObj(Long companyId) {
        return saleGoodsMapper.selectSaleGoodsCustObj(companyId);
    }

    /**
     * 根据销货单状态查询
     *
     * @param saleGoodsOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsByStatus(SaleGoodsOrder saleGoodsOrder) {
        return saleGoodsMapper.selectSaleGoodsByStatus(saleGoodsOrder);
    }

    /**
     * 查询所有的销货单信息
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public SaleGoodsOrder selectSaleGoodsByIds(HashMap<String, Object> hashMap) {
        return saleGoodsMapper.selectSaleGoodsByIds(hashMap);
    }

    /**
     * 出库审核 通过后 修改库存
     *
     * @param
     */
    @Override
    @Transactional
    public void outboundAudit(SaleGoodsOrder saleGoodsOrder) {
        //根据主键查询数据，判断是否含有产品规格型号子集
        HashMap hashMap = new HashMap();
        hashMap.put("saleGoodsId", saleGoodsOrder.getSaleGoodsId());
        SaleGoodsOrder saleGoodsOrder1 = saleGoodsMapper.selectSaleGoodsById(hashMap);
        if ("2".equals(saleGoodsOrder.getSaleGoodsStatus())) {
            saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
        } else {
            if (saleGoodsOrder1.getSaleGoodsModels() != null) {
                //循环插入库存数据
                List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder1.getSaleGoodsModels();
                WarehousingRecords warehousingRecords = new WarehousingRecords();
                for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
                    int allnum = saleGoodsModel.getAllNum();
                    //找库存表 获取id
                    Warehousing warehousing = new Warehousing();
                    warehousing.setDeptId(saleGoodsOrder1.getDeptId());
                    warehousing.setProductId(saleGoodsModel.getProductId());
                    warehousing.setProductType(saleGoodsModel.getProductType());
                    warehousing.setSelectId(saleGoodsModel.getProductId());
                    warehousing.setBatch(saleGoodsModel.getBatch());
                    Warehousing warehousing1 = warehousingMapper.selectWarehousing(warehousing);
                    //存储本次减少的数量
                    warehousingRecords.setInventoryNum(-saleGoodsModel.getNum());
                    warehousingRecords.setAllnum(-allnum);

                    //判断是否拥有该公司该产品该型号名称的库存记录
                    if (warehousing1 == null) {
                        Long b = Long.valueOf(allnum);
                        warehousing.setAmount(b);
                        warehousingMapper.insertWarehousing(warehousing);
                    } else {
                        Long warehousingNum = warehousing1.getAmount();
                        //int warehousingNum = warehousing1.getWarehousingNum();
                        Long num1 = warehousingNum - allnum;
                        warehousing.setAmount(num1);
                        warehousing.setWarehousingId(warehousing1.getWarehousingId());
                        if (num1 < 0) {
                            new AjaxResult(AjaxResult.Type.ERROR, "库存不足");
                            throw new RuntimeException("库存不足");
                        }
                        warehousingMapper.updateWarehousing(warehousing);
                    }

                    Long warehousingId = warehousing.getWarehousingId();
                    warehousingRecords.setOrderNum(saleGoodsOrder1.getSaleGoodsNum());
                    warehousingRecords.setWarehousingId(warehousingId);
                    warehousingRecords.setSupplierId(saleGoodsOrder1.getCustomerId());
                    warehousingRecords.setInventoryStatus("1");
                    warehousingRecords.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                    warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);
                }

                //若选择了 采购订单 则改变采购订单子表的 出库数量
//                Set<Long> purModelIdSet = new HashSet();
//
//                for (int i = 0; i < saleGoodsModels.size(); i++) {
//                    purModelIdSet.add(saleGoodsModels.get(i).getPurchaseModelId());
//                }
//
//                ArrayList<HashMap<Long,Integer>> arrayList = new ArrayList<>();
//
//                //key: purchaseModelId
//                //value: num
//                for (Long next : purModelIdSet) {
//                    HashMap<Long,Integer> map = new HashMap<>();
//                    map.put(next, 0);
//                    arrayList.add(map);
//                }
//
//                for (int i = 0; i < saleGoodsModels.size(); i++) {
//                    SaleGoodsModel saleGoodsModel = saleGoodsModels.get(i);
//                    for (int j = 0; j < arrayList.size(); j++) {
//                        HashMap<Long, Integer> longIntegerHashMap = arrayList.get(j);
//                        Integer integer = null;
//                        try{
//                            integer = longIntegerHashMap.get(saleGoodsModel.getPurchaseModelId());
//                            longIntegerHashMap.put(saleGoodsModel.getPurchaseModelId(),integer+saleGoodsModel.getNum());
//                        }catch (Exception e){
//                            continue;
//                        }
//                    }
//                }
//
//                for (int i = 0; i < arrayList.size(); i++) {
//                    HashMap<Long, Integer> longIntegerHashMap = arrayList.get(i);
//                    Set<Long> longs = longIntegerHashMap.keySet();
//                    Iterator<Long> iterator = longs.iterator();
//                    while (iterator.hasNext()){
//                        //model id
//                        Long modelId = iterator.next();
//                        //num
//                        Integer integer = longIntegerHashMap.get(modelId);
//                        //先查出来原来出库的数量 累加
//                        PurchaseModel purModel = purchaseOrderMapper.selectPurchaseModelByModelId(modelId);
//                        PurchaseModel purchaseModel = new PurchaseModel();
//                        purchaseModel.setModelId(modelId);
//                        purchaseModel.setOutNum(purModel.getOutNum()+integer);
//                        purchaseModel.setPurchaseNum(purModel.getPurchaseNum());
//                        purchaseOrderMapper.updatePurchaseModel(purchaseModel);
//                    }
//                }
            }
        }
    }

    /**
     * 查询销货单的销货单子表数据
     *
     * @param saleGoodsId 销货单主键
     * @return 结果
     */
    @Override
    public List<SaleGoodsModel> selectSaleGoodsModelById(Long saleGoodsId) {
        return saleGoodsMapper.selectSaleGoodsModelById(saleGoodsId);
    }

    /**
     * 查询销货单子表数据集
     *
     * @param saleGoodsModel 销货单子表查询条件
     * @return 结果
     */
    @Override
    public SaleGoodsModel selectSaleGoodsModelByIds(SaleGoodsModel saleGoodsModel) {
        return saleGoodsMapper.selectSaleGoodsModelByIds(saleGoodsModel);
    }

    /**
     * 查询销货单子表数据集合
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsModel> selectSaleGoodsModelByMap(HashMap hashMap) {
        return saleGoodsMapper.selectSaleGoodsModelByMap(hashMap);
    }

    /**
     * 查询销货单子表数据
     *
     * @param saleGoodsModelId 销货单子表主键
     * @return 结果
     */
    @Override
    public SaleGoodsModel selectSaleGoodsModelByModelId(Long saleGoodsModelId) {
        return saleGoodsMapper.selectSaleGoodsModelByModelId(saleGoodsModelId);
    }

    /**
     * 查询销售订单剩余
     *
     * @param saleGoodsId 销货单主键
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsResidue(Long saleGoodsId) {
        return saleGoodsMapper.selectSaleGoodsResidue(saleGoodsId);
    }

    /**
     * 查询采购入库的数据集合
     *
     * @param saleGoodsId 销货单主键
     * @return 结果
     */
    @Override
    public List<Product> selectProcurementByIds(Long saleGoodsId) {
        return saleGoodsMapper.selectProcurementByIds(saleGoodsId);
    }

    /**
     * 查询销货单数据集合
     *
     * @param saleGoodsOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsLists(SaleGoodsOrder saleGoodsOrder) {
        return saleGoodsMapper.selectSaleGoodsLists(saleGoodsOrder);
    }

    /**
     * 修改销货单状态
     *
     * @param hashMap 需要修改的数据
     * @return 结果
     */
    @Override
    public int updateSaleGoodsStatus(HashMap hashMap) {
        return saleGoodsMapper.updateSaleGoodsStatus(hashMap);
    }

    @Override
    public int updateBackNum(HashMap hashMap) {
        return saleGoodsMapper.updateBackNum(hashMap);
    }

    /**
     * 根据库存条件查询销货单子表数据集合
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsModel> selectSaleGoodsModelWarehousingOrderIsSuppByMap(HashMap hashMap) {
        return saleGoodsMapper.selectSaleGoodsModelWarehousingOrderIsSuppByMap(hashMap);
    }

    /**
     * 查询订单审核 中销售退货信息
     *
     * @param saleGoodsId 查询条件
     * @return 结果
     */
    @Override
    public List<Product> selectSaleGoodsModelByNo(Long saleGoodsId) {
        return saleGoodsMapper.selectSaleGoodsModelByNo(saleGoodsId);
    }

    /**
     * 查询销货单列表
     *
     * @param saleGoodsOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsListes(SaleGoodsOrder saleGoodsOrder) {
        return saleGoodsMapper.selectSaleGoodsListes(saleGoodsOrder);
    }

    /**
     * 查询销售商品展示清单
     *
     * @param saleGoodsOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsShowList(SaleGoodsOrder saleGoodsOrder) {
        List<SaleGoodsOrder> list = saleGoodsMapper.selectSaleGoodsShowList(saleGoodsOrder);
        // 解决序列化过滤 null 的操作
        list.forEach(item -> {
            item.setExpressStatus("".equals(item.getExpressStatus()) || null == item.getExpressStatus() ? "0" : item.getExpressStatus());
        });
        return list;
    }

    /**
     * 通过状态选择销售货物客户对象
     *
     * @param companyId 公司逐渐
     * @return 查询条件
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsCustObjByStatus(Long companyId) {
        return saleGoodsMapper.selectSaleGoodsCustObjByStatus(companyId);
    }

    /**
     * 查询销货单数量及批次
     *
     * @param map 查询条件
     * @return 结果
     */
    @Override
    public SaleGoodsModel selectSaleModelByMap(Map<String, Object> map) {
//        return saleGoodsMapper.selectSaleModelByMap(map);
        List<SaleGoodsModel> saleGoodsModels = saleGoodsMapper.selectSaleModelListByMap(map);
        SaleGoodsModel saleGoodsModel = new SaleGoodsModel();
        if (saleGoodsModels.size() != 0) {
            saleGoodsModel = saleGoodsModels.get(0);
        }
        return saleGoodsModel;
    }

    /**
     * 查询销货单数量及批次
     *
     * @param map 查询条件
     * @return 结果
     */
    @Override
    public SaleGoodsOrder selectSaleGoodsByMap(Map<String, Object> map) {
        return saleGoodsMapper.selectSaleGoodsByMap(map);
    }

    /**
     * 查询销货单子表数据
     *
     * @param saleGoodIdList 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsModel> selectSaleGoodsModelByList(List<Long> saleGoodIdList, Long deptId) {
        return saleGoodsMapper.selectSaleGoodsModelByList(saleGoodIdList, deptId);
    }

    /**
     * 插入销货单 选择销售订单的数量
     *
     * @param saleNumRecords 需要插入的数据
     * @return 结果
     */
    @Override
    public int insertSaleNumRecordList(List<SaleNumRecord> saleNumRecords) {
        return saleGoodsMapper.insertSaleNumRecordList(saleNumRecords);
    }

    /**
     * 状态机工厂
     */
    private ServiceFactory factory;
    public SaleGoodsServiceImpl(ServiceFactory factory) {
        this.factory = factory;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditSale(SaleGoodsOrder saleGoodsOrder) {
        StatusService statusService = factory.query(saleGoodsOrder.getSaleGoodsStatus());
        return statusService.execute(saleGoodsOrder);
    }

    /**
     * 按列表选择销售商品型号
     *
     * @param maps 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsModel> selectSaleGoodsModelByListes(List<Map> maps) {
        return saleGoodsMapper.selectSaleGoodsModelByListes(maps);
    }

    /**
     * 查询PDA选择销售商品清单
     *
     * @param saleGoodsOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleGoodsOrder> selectSaleGoodsListByPDA(SaleGoodsOrder saleGoodsOrder) {
        saleGoodsOrder.setDeptId(SecurityUtils.getDeptId());
        return saleGoodsMapper.selectSaleGoodsListByPDA(saleGoodsOrder);
    }

    /**
     * 确认开票信息
     *
     * @param saleGoodsOrder 开票信息
     * @return 结果
     */
    @Override
    public int updateSaleorderOrderIsPay(SaleGoodsOrder saleGoodsOrder) {
        return saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
    }

    /**
     * 查看销货订单的数据
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public SaleGoodsOrder selectSaleGoodsByIdIsLook(HashMap hashMap) {
        return saleGoodsMapper.selectSaleGoodsByIdIsLook(hashMap);
    }

    @Override
    public List<SaleGoodAfter> selectAfterList(Long deptId) {
        return saleGoodsMapper.selectAfterList(deptId);
    }

    @Override
    public int selectSaleGoodsBySaleorderNum(String saleorderNum) {
        return saleGoodsMapper.selectSaleGoodsBySaleorderNum(saleorderNum);
    }

    @Override
    public Long querypreviousId(Long saleGoodsId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("saleGoodsId", saleGoodsId);
        params.put("deptId", SecurityUtils.getDeptId());
        return saleGoodsMapper.querypreviousId(params);
    }

    @Override
    public Long queryNextId(Long saleGoodsId) {
        Map<String, Object> params = new HashMap<>();
        params.put("saleGoodsId", saleGoodsId);
        params.put("deptId", SecurityUtils.getDeptId());
        return saleGoodsMapper.queryNextId(params);
    }

    @Autowired
    ExpressDeliveryService expressDeliveryService;

    @Override
    public Map<String, Object> shipments(String saleGoodsId) {
        // 获取订单
        HashMap<String, Object> saleGoodQueryParams = new HashMap<>();
        saleGoodQueryParams.put("saleGoodsId", saleGoodsId);
        // 获取当前销货单
        SaleGoodsOrder saleGoodsOrder = saleGoodsMapper.selectSaleGoodsById(saleGoodQueryParams);

        // 检查当前订单是否是已批准
        if (null == saleGoodsOrder.getSaleGoodsStatus() || saleGoodsOrder.getSaleGoodsStatus().isEmpty() || !"1".equals(saleGoodsOrder.getSaleGoodsStatus())) {
            throw new RuntimeException("当前订单未审批!");
        }

        // 是否有收货人信息
        // 销货订单号
        String saleGoodsOrderNumber = saleGoodsMapper.selectsalenuma(saleGoodsOrder.getSaleGoodsNum());
        Company company = companyMapper.selectCompany(SecurityUtils.getLoginUser().getCompanyId());
        ExpressDelivery list = expressDeliveryService.selectExpressDelivery(saleGoodsOrderNumber);

        if (ObjectUtils.isEmpty(list)) {
            throw new RuntimeException("当前订单无收货地址,下单失败!");
        }
        list.setFhdz(company.getRasProvince() + company.getRasCity() + company.getRasDistrict() + company.getRasAddress());
        String shName = list.getShname(); // 收货人
        String shPhone = list.getPhone(); // 收货人手机号
        String shAddress = list.getShaddress(); // 收货地址
        if (shName.isEmpty() || shPhone.isEmpty() || shAddress.isEmpty()) {
            throw new RuntimeException("收货信息为空,已取消发货!");
        } else {
            // 构建 发货信息
            Map<String, Object> msgData = new HashMap<>();

            msgData.put("language", "zh-CN");
            msgData.put("orderId", saleGoodsOrder.getOrderId());
            msgData.put("expressTypeId", "2");
            msgData.put("isReturnRoutelabel", "1");

            Map<String, Object> customsInfo = new HashMap<>();
            customsInfo.put("declaredValue", "");
            msgData.put("customsInfo", customsInfo);

            List<Map<String, Object>> cargoDetails = new ArrayList<>();
            // 获取销货单内的产品
            List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder.getSaleGoodsModels();
            for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
                Map<String, Object> cargoItem = new HashMap<>();
                cargoItem.put("amount", "");
                cargoItem.put("count", saleGoodsModel.getNum()); // 出库数量
                cargoItem.put("currency", "");
                cargoItem.put("goodPrepardNo", "");
                cargoItem.put("hsCode", "");
                cargoItem.put("name", saleGoodsModel.getProductName()); // 产品名称
                cargoItem.put("productRecordNo", "");
                cargoItem.put("sourceArea", "CHN");
                cargoItem.put("taxNo", "");
                cargoItem.put("unit", saleGoodsModel.getUnit());
                cargoItem.put("weight", "");
                cargoDetails.add(cargoItem);
            }
            msgData.put("cargoDetails", cargoDetails);

            List<Map<String, Object>> extraInfoList = new ArrayList<>();
            for (int i = 0; i < 6; i++) {
                Map<String, Object> extra = new HashMap<>();
                extra.put("attrName", "");
                extra.put("attrVal", "");
                extraInfoList.add(extra);
            }
            msgData.put("extraInfoList", extraInfoList);

            List<Map<String, Object>> contactInfoList = new ArrayList<>();

            Map<String, Object> receiver = new HashMap<>(); // 收货信息
            receiver.put("address", list.getShaddress()); // 收货地址
            receiver.put("city", "");
            receiver.put("contact", list.getShname()); // 收货人
            receiver.put("contactType", 2);
            receiver.put("country", "CN");
            receiver.put("county", "");
            receiver.put("mobile", list.getPhone()); // 收货人手机号
            receiver.put("postCode", "");
            receiver.put("province", "");
            receiver.put("tel", "");
            contactInfoList.add(receiver);

            Map<String, Object> sender = new HashMap<>(); // 发货信息
            String address = company.getShipProvince() + company.getShipCity() + company.getShipDistrict() + company.getShipAddress();
            sender.put("address", address); // 发货地址(当前公司的发货地址)
            sender.put("city", "");
            sender.put("company", "顺丰速运");
            sender.put("contact", saleGoodsOrder.getUserName()); // 当前订单的负责人姓名
            sender.put("contactType", 1);
            sender.put("country", "CN");
            sender.put("county", "");
            sender.put("mobile", saleGoodsOrder.getPhone()); // 当前订单的负责人手机号
            sender.put("postCode", "");
            sender.put("province", "");
            sender.put("tel", "");
            contactInfoList.add(sender);

            msgData.put("contactInfoList", contactInfoList);

            // 快递月结号
            Company company1 = companyMapper.selectByCompanyId(company.getCompanyId());
            MonthlyCardMsg monthlyCardMsgByCompanyId = monthlyCardMsgMapper.findMonthlyCardMsgByCompanyId(company.getCompanyId());
            // 公司有月结号 并且月结号消息状态为已同步
            if (StringUtils.isNotEmpty(company1.getMonthlyCard()) && "2".equals(monthlyCardMsgByCompanyId.getStatus())) {
                msgData.put("monthlyCard", company1.getMonthlyCard());
            } else if (StringUtils.isNotEmpty(company1.getMonthlyCard()) && (null != monthlyCardMsgByCompanyId && "1".equals(monthlyCardMsgByCompanyId.getStatus()))) {
                msgData.put("cargoDesc", "请使用"+ company1.getMonthlyCard() +"进行结算");
            }

            // 订单号
            String saleOrderNumber = saleGoodsOrder.getSaleGoodsNum();
            // 收货手机号
            String recipientsPhone = list.getPhone();
            if (recipientsPhone.isEmpty()) {
                throw new RuntimeException("收货人手机号为空! 下单失败");
            }
            // 发货手机号
            String senderPhone = saleGoodsOrder.getPhone();
            if (senderPhone.isEmpty()) {
                throw new RuntimeException("发货人手机号为空! 下单失败");
            }
            String jsonString = JSONUtils.toJSONString(msgData);

            // 调用发货
            Map<String, Object> sfResult;
            try {
                sfResult = expressDeliveryService.placeOrder(jsonString, saleOrderNumber, recipientsPhone, senderPhone);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("发货失败!");
            }
            // 更改订单的快递状态
            if ("0".equals(saleGoodsOrder.getExpressStatus())) {
                String expressStatus = 200 ==  (Integer) sfResult.get("code") ? "1" : "2";
                saleGoodsMapper.updateExpressStatusBySaleGoodsId(saleGoodsOrder.getSaleGoodsId(), expressStatus);
            }
            return sfResult;
        }
    }

    @Override
    public Map<String, Object> printExpressOrder(Long saleGoodsId) {
        // 获取订单
        HashMap<String, Object> params = new HashMap<>();
        params.put("saleGoodsId", saleGoodsId);
        SaleGoodsOrder saleGoodsOrder = saleGoodsMapper.selectSaleGoodsById(params);
        // 获取订单的快递单号
        List<ExpressDelivery> expressDeliveries = expressDeliveryService.selectSfInformation(saleGoodsOrder.getSaleGoodsNum());

        // 构建msgData
        HashMap<String, Object> msgDataMap = buildMsgData(expressDeliveries, saleGoodsOrder);
        String msgData = JSON.toJSONString(msgDataMap);
        // 获取订单号
        Map<String, Object> result;
        try {
            result = expressDeliveryService.PrintSheet(msgData);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 快递包裹详情
     * @param saleGoodsOrder
     * @return
     */
    private static String buildExpressInfo(SaleGoodsOrder saleGoodsOrder) {
        List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder.getSaleGoodsModels();
        String result = saleGoodsModels.stream()
                .map(model -> model.getProductName() + " (" + model.getProductType() + ") x " + model.getNum())
                .collect(Collectors.joining(", "));
        return result;
    }

    private static HashMap<String, Object> buildMsgData(List<ExpressDelivery> expressDeliveries, SaleGoodsOrder saleGoodsOrder) {
        String waybillNo = expressDeliveries.get(0).getWaybillNo();
        HashMap<String, Object> msgDataMap = new HashMap<>();
        msgDataMap.put("templateCode", "fm_76130_standard_Y73UO5YO"); // fm_76130_standard_Y73UO5YO
        msgDataMap.put("version", 2.0);
        msgDataMap.put("fileType", "pdf");
        msgDataMap.put("sync", true);


        List<Map<String, String>> documents = new ArrayList<>();
        HashMap<String, String> document = new HashMap<>();
        document.put("masterWaybillNo", waybillNo);
        String expressInfo = buildExpressInfo(saleGoodsOrder);
        document.put("remark", expressInfo);
        documents.add(document);
        msgDataMap.put("documents", documents);
        return msgDataMap;
    }

    @Override
    public List<SaleGoodsExcel> queryExcel(SaleGoodsExcel saleGoodsExcel) {
        // 默认本月第一天至今天(默认时间由前端控制)
        // if (ObjectUtil.isEmpty(saleGoodsExcel.getStartTime()) || ObjectUtil.isEmpty(saleGoodsExcel.getEndTime())) {
        //     LocalDate now = LocalDate.now();              // 当前日期
        //     LocalDate firstDay = now.withDayOfMonth(1);   // 当月第一天
        //     saleGoodsExcel.setStartTime(firstDay);
        //     saleGoodsExcel.setEndTime(now);
        // }

        Long deptId = SecurityUtils.getDeptId();
        saleGoodsExcel.setDeptId(deptId);
        return saleGoodsMapper.queryExcel(saleGoodsExcel);
    }

    @Override
    public List<Map<String, Object>> pendingReview(Long deptID) {
        return saleGoodsMapper.pendingReview(deptID)
                .stream()
                .peek(item -> item.put("orderType", "销货订单"))
                .collect(Collectors.toList());
    }

    @Override
    public Integer selectCountByDeptIDAndStatus(Long deptID) {
        return 0;
    }
}
